package com.maxd.component.sequence;

import com.maxd.error.ExceptionEnum;
import com.maxd.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SeqTools {

    private static final long[] LONG_ARRAY = {10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L};


    private static SeqComponent seqComponent;

    @Autowired
    private void setSeqComponent(DBSeqComponent seqComponent) {
        SeqTools.seqComponent = seqComponent;
    }

    public static String dbId(String prefix) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        return prefix + dateStr + seq(SeqScene.DB_ID, 6);
    }
    /**
     * yyyyMMddHHmmss + 10位数字
     * @return
     */
    public static String dateSeq() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(new Date());
        return dateStr + seq(SeqScene.COMMON_SEQ, 10);
    }

    public static String seq(SeqScene scene, int length) {
        AssertUtil.assertTrue(length <= LONG_ARRAY.length, ExceptionEnum.SEQ_LENGTH_ERROR);
        long seq = seqComponent.seq(scene);
        seq = seq % LONG_ARRAY[length - 1];
        return String.format("%0" + length + "d", seq);
    }
}
